<?php

class Elem_questions_model extends Onecore_Model
{
    public $answers_model;
    public $_questions;
    public $_questionsList;
    public $cfg;
    public function __construct()
    {
        parent::__construct();
        $this->_name = "elem_questions";
        $this->_id = array("id");
        $this->_fields = array("id","index","description","type_questions_id","elem_test_id","parent","type_object_parent_id");
        $this->_fieldsConditions = array("ModuloId"=>"where","name"=>"like","description"=>"like");
        $this->_itemName = "Pregunta";
        $this->_validations = array(
            array(
                "field"=>"description",
                "label"=>"Respuesta",
                "rules"=>"required"
            )  ,
            array(
                "field"=>"type_questions_id",
                "label"=>"Tipo Pregunta",
                "rules"=>"required"
            )  ,
            array(
                "field"=>"elem_test_id",
                "label"=>"Identificador de Prueba",
                "rules"=>"required"
            )  
        );

        $this->load->model("elem_questions_answers_model");
        $this->answers_model = $this->elem_questions_answers_model;
        $this->cfg = (object)$this->config->item("defaultCfg");
    }   

    public function getRandom($options){
        if(!empty($options->excluded)){
            if(!is_array($options->excluded)){
                $aux = array();
                foreach ($options->questions as $q) {
                    if($q->id != $options->excluded){
                        $aux[] = $q;
                    }
                }
            }
            else{
                $aux = array();
                foreach ($options->questions as $q) {
                    foreach($options->excluded as $exclude){
                        if($q->id != $exclude){
                            $aux[] = $q;
                        }    
                    }
                }
            }
            shuffle($aux);
            return $aux[0];
        }
       
    }


    public function getQuestionsByTest($test_id, $options=null){
        $this->load->model("elem_questions_answers_model");
        $questions = $this->getByelem_test_id($test_id);
        $rows = array();
        $i = 1;
        foreach($questions as $question){
            $answers = $this->elem_questions_answers_model->getByelem_questions_id($question->id);
            $question->answers = $answers;
            //tratamiento especial respuesta tipo terminos pareados
            if($question->type_questions_id == 2){
                $question = $this->elem_questions_answers_model->getInnerAnswersFormat($question);
            }
            if($options!= null && !empty($options->removeHTML) && $options->removeHTML == "true"){
                $question->description = html_entity_decode($question->description);
                $question->description = str_replace("<p>", "", $question->description);
                $question->description = str_replace("<em>", "", $question->description);
                $question->description = str_replace("<strong>", "", $question->description);
                $question->description = str_replace("</strong>", "", $question->description);
                $question->description = str_replace("</em>", "", $question->description);
                $question->description = str_replace("</p>", "", $question->description);
                $question->description = str_replace("&nbsp;", "", $question->description);
                $question->description = preg_replace("/&#?[a-z0-9]+;/i","",$question->description);
                $question->description = $i.".- ".$question->description;
                $i++;
            }
            else{
                $question->description = str_replace("&nbsp;", " ", $question->description);
                $question->description = html_entity_decode($question->description);
            }

            for($i=0;$i<count($question->answers);$i++){
                $question->answers[$i]->description = str_replace("&nbsp;", " ", $question->answers[$i]->description);
                $question->answers[$i]->explication = str_replace("&nbsp;", " ", $question->answers[$i]->explication);
                $question->answers[$i]->description = html_entity_decode($question->answers[$i]->description);
                $question->answers[$i]->explication = html_entity_decode($question->answers[$i]->explication);
            }
                
            $rows[] = $question;
        }
        return $rows;
    }


    //permite obtener el formato de preguntas anexadas
    public function getInnerQuestionsFormat($question){
        $aux = $question->answers;
        $aux2 = $question->answers;
        $answers = array();
        $answers2 = array();
        foreach ($aux as $a) {
            if($a->parent == 0){
                foreach ($aux2 as $a2) {
                    if($a2->parent == $a->id){
                        $a->answer = $a2;
                        $answers2[] = $a2;
                    }
                }
                $answers[] = $a;
            }
        }
        $question->answers = $answers;
        $question->innerAnswers = $answers2;
        return $question;
    }
    public function getInnerQuestionsByParent($cfg){
        $sql = "select * 
                from $this->_name 
                where type_object_parent_id = $cfg->type_object_parent_id
                and parent = $cfg->parent";

        $query = $this->db->query($sql);
        return $query->result();       
    }

    /*
    *   parent: Identificador de entidad padre
        type: identificador de tipo de entidad padre
        question_id: identificador de la pregunta  asociada a l respuesta
        deep: profundidad inicial del padre (pregunta)
    */

    public function getQuestionsByParentM($parent,$type, $question_id, $deep){
        $res = array();
        for($i=0;$i<count($this->_questions);$i++){
            if($this->_questions[$i]->parent == $parent 
                && $this->_questions[$i]->type_object_parent_id == $type
                && $this->_questions[$i]->id != $question_id){
                $res[] = $this->_questions[$i];
                $this->_questions[$i]->looked = true;
                $this->_questions[$i]->deep = $deep+1;

                $this->_questionsList[] = $this->_questions[$i];

            }
        }
        return $res;
    }

    public function getTreeByAnswer($parent,$_question_id, $deep){
        $_qres = array();
        //obtengo todas las preguntas asociadas a una respuesta
        $questions = $this->getQuestionsByParentM($parent, $this->cfg->type_object_answer, $_question_id, $deep);
//        log_message("error","(getTreeByAnswer) parent: $parent, question_id: $_question_id, n: ".count($questions));

        if(!empty($questions)){
            foreach($questions as $question){
 //               log_message("error","(getTreeByAnswer) Evaluando sub-question: $question->id");    
                $answers2 = array();
                //por cada respuesta llamo al metodo recursivo
                foreach ($question->answers as $answer) {
                    $iQuestions = $this->getTreeByAnswer($answer->id,$question->id, $question->deep); //<------ recursivo vuelve aqui
                    if(!empty($iQuestions))
                        $answer->questions = $iQuestions;
                    $answers2[] = $answer;
                }
                $question->answers = $answers2;
                $question->processed = true;
                $_qres[] = $question;
            }
        }

  //      log_message("error","(getTreeByAnswer) return ".count($_qres));

        return $_qres;
    }

    public function getTree(){
        $q = array();
        foreach($this->_questions as $question){
 //           log_message("error","(getTree) Evaluando question: $question->id");
            if(!$question->looked){
                
                $this->_questionsList[] = $question;

                foreach ($question->answers as $answer) {
                    $aux = $this->getTreeByAnswer($answer->id, $question->id, $question->deep );
                    if(!empty($aux) && count($aux)>0)   
                        $answer->questions = $aux;
                }
                $q[] = $question;
            }
            else{
 //               log_message("error","(getTree) question: $question->id ya fue procesada");
            }
        }
        return $q;
    }
    //permite obtener una lista simple ordenada segun parent, childs y deep de cada question
    public function getListFromTree($tree){
        $res = array();

    }

}